const app = require('express')();
const { default: axios } = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();

app.use(bodyParser.json());
app.use(cors());

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/api/getCode', async (req, res) => {
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
    process.env.APPID
  }&redirect_uri=${encodeURIComponent(
    'http://10.250.221.41:3000'
  )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  res.send(url);
});

app.post('/api/getUserInfo', async (req, res) => {
  const { code } = req.body;
  const access_token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${process.env.APPID}&secret=${process.env.APPSECRET}&code=${code}&grant_type=authorization_code`;
  const { access_token, openid } = (await axios.get(access_token_url)).data;
  const userinfo_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
  const userinfo = (await axios.get(userinfo_url)).data;
  res.send(userinfo);
});

app.listen(5173, () => {
  console.log('listening on port 5173');
});
